<template>
	<div class="business-wallet">
		<div class="header">
			<h2>商家钱包</h2>
		</div>

		<!-- 钱包概览 -->
		<div class="wallet-overview">
			<div class="balance-card">
				<div class="balance-info">
					<h3>钱包余额</h3>
					<div class="balance-amount">¥{{ walletInfo.availableBalance || walletInfo.walletBalance || '232.00' }}</div>
					<div class="available-balance">
						今日收益: ¥{{ todayStats.totalReceived || '0.00' }}
					</div>
				</div>
				<div class="balance-actions">
					<button @click="showWithdrawDialog = true" class="withdraw-btn">提现</button>
					<button @click="refreshWalletInfo" class="refresh-btn">刷新</button>
				</div>
			</div>

			<div class="stats-cards">
				<div class="stat-card">
					<h4>今日收益</h4>
					<div class="stat-value">¥{{ todayStats.totalReceived || '0.00' }}</div>
					<div class="stat-detail">订单数: {{ todayStats.orderCount || 0 }}</div>
				</div>
				<div class="stat-card">
					<h4>本月收益</h4>
					<div class="stat-value">¥{{ monthlyStats.totalReceived || '0.00' }}</div>
					<div class="stat-detail">订单数: {{ monthlyStats.orderCount || 0 }}</div>
				</div>
				<div class="stat-card">
					<h4>平台手续费</h4>
					<div class="stat-value">¥{{ walletInfo.totalPlatformFee || '0.00' }}</div>
					<div class="stat-detail">累计扣除</div>
				</div>
			</div>
		</div>

		<!-- 交易记录 -->
		<div class="transaction-section">
			<h3>交易记录</h3>
			<div class="transaction-list">
				<div v-if="transactions.length === 0" class="no-transactions">
					暂无交易记录
				</div>
				<div v-else>
					<div v-for="transaction in transactions" :key="transaction.trans_id" class="transaction-item">
						<div class="transaction-info">
							<div class="transaction-type">
								{{ getTransactionTypeText(transaction.transaction_type) }}
							</div>
							<div class="transaction-desc">{{ transaction.description || '订单收款' }}</div>
							<div class="transaction-time">{{ formatTime(transaction.create_time) }}</div>
						</div>
						<div class="transaction-amount" :class="getAmountClass(transaction)">
							{{ getAmountText(transaction) }}
						</div>
					</div>
				</div>
			</div>
			<div class="pagination" v-if="transactions.length > 0">
				<button @click="loadPreviousPage" :disabled="currentPage <= 1">上一页</button>
				<span>第 {{ currentPage }} 页</span>
				<button @click="loadNextPage" :disabled="transactions.length < pageSize">下一页</button>
			</div>
		</div>

		<!-- 提现对话框 -->
		<div v-if="showWithdrawDialog" class="dialog-overlay" @click="closeWithdrawDialog">
			<div class="dialog" @click.stop>
				<h3>钱包提现</h3>
				<div class="form-group">
					<label>提现金额</label>
					<input 
						v-model="withdrawForm.amount" 
						type="number" 
						step="0.01" 
						placeholder="请输入提现金额"
						class="form-input"
					>
				</div>
				<div class="form-group">
					<label>支付密码</label>
					<input 
						v-model="withdrawForm.payPwd" 
						type="password" 
						placeholder="请输入支付密码"
						class="form-input"
					>
				</div>
				<div class="dialog-actions">
					<button @click="closeWithdrawDialog" class="cancel-btn">取消</button>
					<button @click="confirmWithdraw" class="confirm-btn" :disabled="isWithdrawing">
						{{ isWithdrawing ? '提现中...' : '确认提现' }}
					</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'BusinessWallet',
	data() {
		return {
			businessId: '', // 从登录信息获取
			walletInfo: {},
			todayStats: {},
			monthlyStats: {},
			transactions: [],
			currentPage: 1,
			pageSize: 20,
			showWithdrawDialog: false,
			withdrawForm: {
				amount: '',
				payPwd: ''
			},
			isWithdrawing: false
		}
	},
	mounted() {
		this.initBusinessId()
		this.loadWalletData()
	},
	methods: {
		// 初始化商家ID
		initBusinessId() {
			// 从Vuex store获取商家ID
			this.businessId = this.$store.state.businessId
			if (!this.businessId) {
				alert('未找到商家信息，请重新登录')
				this.$router.push('/login')
				return
			}
		},

		// 加载钱包数据
		async loadWalletData() {
			try {
				await Promise.all([
					this.loadWalletInfo(),
					this.loadTodayStats(),
					this.loadMonthlyStats(),
					this.loadTransactions()
				])
			} catch (error) {
				console.error('加载钱包数据失败:', error)
				alert('加载钱包数据失败')
			}
		},

		// 获取钱包信息
		async loadWalletInfo() {
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/getWalletInfo', null, {
					params: { businessId: this.businessId }
				})
				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					this.walletInfo = response.data.result || {}
				} else {
					throw new Error(response.data?.message || '获取钱包信息失败')
				}
			} catch (error) {
				console.error('获取钱包信息失败:', error)
				// 如果钱包不存在，尝试初始化
				if (error.message && error.message.includes('不存在')) {
					await this.initWallet()
				}
			}
		},

		// 获取今日统计
		async loadTodayStats() {
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/getTodayStats', null, {
					params: { businessId: this.businessId }
				})
				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					this.todayStats = response.data.result || {}
				}
			} catch (error) {
				console.error('获取今日统计失败:', error)
			}
		},

		// 获取月度统计
		async loadMonthlyStats() {
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/getMonthlyStats', null, {
					params: { businessId: this.businessId }
				})
				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					this.monthlyStats = response.data.result || {}
				}
			} catch (error) {
				console.error('获取月度统计失败:', error)
			}
		},

		// 获取交易记录
		async loadTransactions() {
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/getTransactions', null, {
					params: { 
						businessId: this.businessId,
						page: this.currentPage,
						size: this.pageSize
					}
				})
				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					this.transactions = response.data.result || []
				}
			} catch (error) {
				console.error('获取交易记录失败:', error)
			}
		},

		// 初始化钱包
		async initWallet() {
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/initWallet', null, {
					params: { businessId: this.businessId }
				})
				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					alert('钱包初始化成功')
					await this.loadWalletInfo()
				}
			} catch (error) {
				console.error('钱包初始化失败:', error)
				alert('钱包初始化失败')
			}
		},

		// 刷新钱包信息
		async refreshWalletInfo() {
			await this.loadWalletData()
			alert('刷新成功')
		},

		// 确认提现
		async confirmWithdraw() {
			if (!this.withdrawForm.amount || !this.withdrawForm.payPwd) {
				alert('请填写完整信息')
				return
			}

			if (parseFloat(this.withdrawForm.amount) <= 0) {
				alert('提现金额必须大于0')
				return
			}

			if (parseFloat(this.withdrawForm.amount) > parseFloat(this.walletInfo.availableBalance || 0)) {
				alert('提现金额不能超过可用余额')
				return
			}

			this.isWithdrawing = true
			try {
				const response = await this.$axios.post('/elm/BusinessWalletController/withdraw', null, {
					params: {
						businessId: this.businessId,
						amount: this.withdrawForm.amount,
						payPwd: this.withdrawForm.payPwd
					}
				})

				if (response.data && (response.data.code === 200 || response.data.code === '200')) {
					alert('提现成功')
					this.closeWithdrawDialog()
					await this.loadWalletData()
				} else {
					throw new Error(response.data?.message || '提现失败')
				}
			} catch (error) {
				console.error('提现失败:', error)
				alert(error.message || '提现失败')
			} finally {
				this.isWithdrawing = false
			}
		},

		// 关闭提现对话框
		closeWithdrawDialog() {
			this.showWithdrawDialog = false
			this.withdrawForm = { amount: '', payPwd: '' }
		},

		// 上一页
		async loadPreviousPage() {
			if (this.currentPage > 1) {
				this.currentPage--
				await this.loadTransactions()
			}
		},

		// 下一页
		async loadNextPage() {
			this.currentPage++
			await this.loadTransactions()
		},

		// 获取交易类型文本
		getTransactionTypeText(type) {
			const typeMap = {
				'ORDER_PAYMENT': '订单收款',
				'WITHDRAWAL': '钱包提现',
				'REFUND': '订单退款',
				'PAYMENT': '收款'
			}
			return typeMap[type] || '其他'
		},

		// 获取金额样式类
		getAmountClass(transaction) {
			// 如果是收款（to_wallet_id是当前商家），显示绿色
			// 如果是支出（from_wallet_id是当前商家），显示红色
			return transaction.to_wallet_id === this.businessId ? 'amount-positive' : 'amount-negative'
		},

		// 获取金额文本
		getAmountText(transaction) {
			const amount = parseFloat(transaction.amount || 0).toFixed(2)
			const platformFee = parseFloat(transaction.platform_fee || 0).toFixed(2)
			
			if (transaction.to_wallet_id === this.businessId) {
				// 收款
				if (platformFee > 0) {
					return `+¥${amount} (手续费: ¥${platformFee})`
				}
				return `+¥${amount}`
			} else {
				// 支出
				return `-¥${amount}`
			}
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			return date.toLocaleString('zh-CN')
		}
	}
}
</script>

<style scoped>
.business-wallet {
	padding: 20px;
	max-width: 1200px;
	margin: 0 auto;
}

.header h2 {
	color: #333;
	margin-bottom: 20px;
}

.wallet-overview {
	display: grid;
	grid-template-columns: 1fr 2fr;
	gap: 20px;
	margin-bottom: 30px;
}

.balance-card {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	padding: 30px;
	border-radius: 15px;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.balance-amount {
	font-size: 2.5em;
	font-weight: bold;
	margin: 10px 0;
}

.available-balance {
	opacity: 0.9;
	font-size: 0.9em;
}

.balance-actions {
	display: flex;
	gap: 10px;
	margin-top: 20px;
}

.withdraw-btn, .refresh-btn {
	padding: 10px 20px;
	border: 2px solid white;
	background: transparent;
	color: white;
	border-radius: 25px;
	cursor: pointer;
	transition: all 0.3s;
}

.withdraw-btn:hover, .refresh-btn:hover {
	background: white;
	color: #667eea;
}

.stats-cards {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 15px;
}

.stat-card {
	background: white;
	padding: 20px;
	border-radius: 10px;
	box-shadow: 0 2px 10px rgba(0,0,0,0.1);
	text-align: center;
}

.stat-card h4 {
	color: #666;
	margin-bottom: 10px;
	font-size: 0.9em;
}

.stat-value {
	font-size: 1.8em;
	font-weight: bold;
	color: #333;
	margin-bottom: 5px;
}

.stat-detail {
	color: #999;
	font-size: 0.8em;
}

.transaction-section {
	background: white;
	padding: 20px;
	border-radius: 10px;
	box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.transaction-section h3 {
	margin-bottom: 20px;
	color: #333;
}

.no-transactions {
	text-align: center;
	color: #999;
	padding: 40px;
}

.transaction-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f0f0f0;
}

.transaction-item:last-child {
	border-bottom: none;
}

.transaction-info {
	flex: 1;
}

.transaction-type {
	font-weight: bold;
	color: #333;
	margin-bottom: 5px;
}

.transaction-desc {
	color: #666;
	font-size: 0.9em;
	margin-bottom: 3px;
}

.transaction-time {
	color: #999;
	font-size: 0.8em;
}

.transaction-amount {
	font-weight: bold;
	font-size: 1.1em;
}

.amount-positive {
	color: #52c41a;
}

.amount-negative {
	color: #ff4d4f;
}

.pagination {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 20px;
	margin-top: 20px;
}

.pagination button {
	padding: 8px 16px;
	border: 1px solid #d9d9d9;
	background: white;
	border-radius: 4px;
	cursor: pointer;
}

.pagination button:disabled {
	opacity: 0.5;
	cursor: not-allowed;
}

.pagination button:not(:disabled):hover {
	border-color: #40a9ff;
	color: #40a9ff;
}

.dialog-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
}

.dialog {
	background: white;
	padding: 30px;
	border-radius: 10px;
	width: 400px;
	max-width: 90vw;
}

.dialog h3 {
	margin-bottom: 20px;
	text-align: center;
	color: #333;
}

.form-group {
	margin-bottom: 20px;
}

.form-group label {
	display: block;
	margin-bottom: 8px;
	color: #333;
	font-weight: bold;
}

.form-input {
	width: 100%;
	padding: 12px;
	border: 1px solid #d9d9d9;
	border-radius: 6px;
	font-size: 14px;
	box-sizing: border-box;
}

.form-input:focus {
	outline: none;
	border-color: #40a9ff;
	box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.2);
}

.dialog-actions {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
	margin-top: 30px;
}

.cancel-btn, .confirm-btn {
	padding: 10px 20px;
	border: none;
	border-radius: 6px;
	cursor: pointer;
	font-size: 14px;
}

.cancel-btn {
	background: #f5f5f5;
	color: #666;
}

.confirm-btn {
	background: #1890ff;
	color: white;
}

.confirm-btn:disabled {
	opacity: 0.6;
	cursor: not-allowed;
}

.cancel-btn:hover {
	background: #e6e6e6;
}

.confirm-btn:not(:disabled):hover {
	background: #40a9ff;
}

@media (max-width: 768px) {
	.wallet-overview {
		grid-template-columns: 1fr;
	}
	
	.stats-cards {
		grid-template-columns: 1fr;
	}
	
	.transaction-item {
		flex-direction: column;
		align-items: flex-start;
		gap: 10px;
	}
}
</style>
